<script setup lang="ts">
import { cloneDeep } from 'lodash-es'
import type { FormInstance } from 'element-plus'
import ElectricityList from './ElectricityList.vue'
import type { CustomDialogInstance } from '@/types/modules/public'
import type { Config, OmitCreationElectricityConfig } from '@/mixins/MixinElectricPriceConfigs'
import { ELECTRICITY_CONFIG_TYPES, getListKey, useElectricPriceConfigs } from '@/mixins/MixinElectricPriceConfigs'

type ElectricityListInstance = InstanceType<typeof ElectricityList>

const props = defineProps<{
  modalTitle: string
  isAdd: boolean
}>()
const emits = defineEmits<{
  (e: 'save-success'): void
}>()
const info = defineModel<OmitCreationElectricityConfig>({ required: true })
const dialogRef = ref<CustomDialogInstance>()
const formRef = ref<FormInstance>()
const tipListRef = ref<ElectricityListInstance>()
const peakListRef = ref<ElectricityListInstance>()
const flatListRef = ref<ElectricityListInstance>()
const valleyListRef = ref<ElectricityListInstance>()
const rules = {
  time: [
    { required: true, message: '请选择开始时间' },
  ],
}
const {
  saveElectricityConfig,
  editElectricityConfig,
  hasConfig,
} = useElectricPriceConfigs()

function handlerAdd(config: Config, type: ELECTRICITY_CONFIG_TYPES) {
  const key = getListKey(type)
  unref(info)[key].push(config)
}
function handlerRemove(index: number, type: ELECTRICITY_CONFIG_TYPES) {
  const key = getListKey(type)
  unref(info)[key].splice(index, 1)
}
function handlerChange(
  { configs }: { index?: number, timerange?: [string, string], configs: Config[] },
  type: ELECTRICITY_CONFIG_TYPES,
) {
  const key = getListKey(type)
  unref(info)[key] = configs
}

function resolveInfo(data: OmitCreationElectricityConfig): OmitCreationElectricityConfig {
  data = cloneDeep(data)
  const done = (array: Config[]) => array.filter(v => v.startTime && v.endTime)
  data.tipList = tipListRef.value?.isChecked() ? done(data.tipList) : []
  data.peakList = peakListRef.value?.isChecked() ? done(data.peakList) : []
  data.flatList = flatListRef.value?.isChecked() ? done(data.flatList) : []
  data.valleyList = valleyListRef.value?.isChecked() ? done(data.valleyList) : []
  return data
}

function checkElectricityLists() {
  unref(tipListRef)?.checkErrors()
  unref(peakListRef)?.checkErrors()
  unref(flatListRef)?.checkErrors()
  unref(valleyListRef)?.checkErrors()
  return !unref(tipListRef)?.hasError()
    && !unref(peakListRef)?.hasError()
    && !unref(flatListRef)?.hasError()
    && !unref(valleyListRef)?.hasError()
}

async function clickSave(done: () => void) {
  const isValid = await formRef.value?.validate().catch(() => {})

  if (!isValid || !checkElectricityLists()) {
    done()
    return
  };
  const params = resolveInfo(unref(info))

  if ([params.tipList, params.peakList, params.flatList, params.valleyList].every(v => v.length === 0)) {
    done()
    ElMessage.warning('请至少添加一条数据')
    return
  }
  try {
    if (props.isAdd) {
      await saveElectricityConfig(params)
    }
    else {
      await editElectricityConfig(params)
    }
    done()
    ElMessage.success('保存成功')
    close()
    emits('save-success')
  }
  catch (e) {
    console.warn(e)
  }
  finally {
    done()
  }
}

function changeTime() {
  const t = unref(info).time
  hasConfig(t)
}
function initialCheckedStatus(configs: Config[]): boolean {
  if (unref(props.isAdd))
    return false
  return configs.some(v => v.startTime && v.endTime && v.price)
}

async function open() {
  unref(tipListRef)?.resetErrors()
  unref(peakListRef)?.resetErrors()
  unref(flatListRef)?.resetErrors()
  unref(valleyListRef)?.resetErrors()
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="modalTitle"
    class="electricity-dialog"
    :no-max-height="true"
    width="740px"
    need-saving
    @confirm="clickSave"
  >
    <ElForm ref="formRef" :model="info" :rules="rules">
      <ElFormItem label="开始时间" required prop="time">
        <ElDatePicker
          v-model="info.time" type="date"
          placeholder="请选择开始时间"
          value-format="YYYY-MM-DD" format="YYYY-MM-DD"
          @change="changeTime"
        />
      </ElFormItem>
      <div class="roll" style="max-height: 50vh;overflow-x: hidden;">
        <ElectricityList
          ref="tipListRef"
          :type="ELECTRICITY_CONFIG_TYPES.TIP" type-text="尖"
          :list="info.tipList" :is-add="isAdd" initial-checked
          @add="handlerAdd($event, ELECTRICITY_CONFIG_TYPES.TIP)"
          @remove="handlerRemove($event, ELECTRICITY_CONFIG_TYPES.TIP)"
          @change="handlerChange($event, ELECTRICITY_CONFIG_TYPES.TIP)"
        />
        <ElectricityList
          ref="peakListRef"
          :type="ELECTRICITY_CONFIG_TYPES.PEAK" type-text="峰"
          :list="info.peakList" :initial-checked="!isAdd && initialCheckedStatus(info.peakList)"
          @add="handlerAdd($event, ELECTRICITY_CONFIG_TYPES.PEAK)"
          @remove="handlerRemove($event, ELECTRICITY_CONFIG_TYPES.PEAK)"
          @change="handlerChange($event, ELECTRICITY_CONFIG_TYPES.PEAK)"
        />
        <ElectricityList
          ref="flatListRef"
          :type="ELECTRICITY_CONFIG_TYPES.FLAT" type-text="平"
          :list="info.flatList" :initial-checked="!isAdd && initialCheckedStatus(info.flatList)"
          @add="handlerAdd($event, ELECTRICITY_CONFIG_TYPES.FLAT)"
          @remove="handlerRemove($event, ELECTRICITY_CONFIG_TYPES.FLAT)"
          @change="handlerChange($event, ELECTRICITY_CONFIG_TYPES.FLAT)"
        />
        <ElectricityList
          ref="valleyListRef"
          :type="ELECTRICITY_CONFIG_TYPES.VALLEY" type-text="谷"
          :list="info.valleyList" :initial-checked="!isAdd && initialCheckedStatus(info.valleyList)"
          @add="handlerAdd($event, ELECTRICITY_CONFIG_TYPES.VALLEY)"
          @remove="handlerRemove($event, ELECTRICITY_CONFIG_TYPES.VALLEY)"
          @change="handlerChange($event, ELECTRICITY_CONFIG_TYPES.VALLEY)"
        />
      </div>
    </ElForm>
  </CustomDialog>
</template>
